package com.hsylient.javase.draftpaper;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class NewAesUtil {

    // 密钥hex值
    private static String hexKey = "qwerqwerqwerq34123412343adsfaada";
    // 初始化加密工具
    private static AES aes;

    /**
     * 初始化aes工具类
     */
    private static AES getAes() {
        if (StrUtil.isBlank(hexKey)) throw new RuntimeException("AES key cannot be empty!");
        if (aes == null)  return aes = SecureUtil.aes(HexUtil.decodeHex(hexKey));
        return aes;
    }

    /**
     * 加密后base64编码
     */
    public static String encryptBase64(String content) {
        return getAes().encryptBase64(content);
    }

    /**
     * 解密base64的字符串
     */
    public static String decryptBase64(String base64Str) {
        return getAes().decryptStr(Base64.decode(base64Str));
    }

    /**
     * 生成随机密钥
     */
    public static String generateKey() {
        SecretKey key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), 256);
        String hexKey = HexUtil.encodeHexStr(key.getEncoded());
        System.out.println("key.getEncoded() = " + Arrays.toString(key.getEncoded()));
        System.out.println("key.getEncoded() = " + new String(key.getEncoded(), StandardCharsets.UTF_8));
        System.out.println("key.getEncoded() = " + hexKey);
        return hexKey;
    }


    public static void main(String[] args) {
        System.out.println(NewAesUtil.encryptBase64("guaaaaaaaaaaaaaaaaess"));
    }
}
